from django.template import Library
import re

register = Library()

def natural_sort(values,key=None):
    #def alphanum_dbg_key(newkey):
    #    print "alphanum mewkey=%s" % str(newkey) if key is None else key(str(newkey))
    #    return [ convert(c) for c in re.split('([0-9]+)',str(newkey) if key is None else key(str(newkey))) ] 
    convert = lambda text: int(text) if text.isdigit() else text.lower() 
    alphanum_key = lambda newkey: [ convert(c) for c in re.split('([0-9]+)', str(newkey) if key is None else str(key(newkey))) ] 
    return sorted(values, key = alphanum_key)
register.filter(natural_sort)

